Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
Using Intersection Observer and EventListeners || Registering keypresses only while specific element is visible

I'm attempting to add an event listener to the document element, which remains active only while a specific section element is within the visible portion of the viewport.

This listener listens for two keypresses, ArrowLeft and ArrowRight, and calls matching functions moveLeft() and moveRight() for each case. Once the section is no longer visible within the viewport the eventListener is to be removed.

const cObserverHandler = entries => {
    const [entry] = entries;

    const keyListener = e => {
        if (e.key === 'ArrowLeft') moveLeft();
        else if (e.key === 'ArrowRight') moveRight();
    };
    if (entry.isIntersecting) {
        console.log('intersect');
        document.addEventListener('keyup', keyListener);
    } else if (!entry.isIntersecting) {
        console.log('depart');
        document.removeEventListener('keyup', keyListener);
    }
};

For brevity I've excluded the IntesectionObserver setup and larger app functioning.

As well, to those not already familiar, within this context entry.isIntersecting will evaluate to a Boolean value based on whether the aforementioned section is within the visible area of the viewport.

El problema:

Examining the console, the messages 'intersect' and 'depart' fire during my scroll testing at the expected times. However, some further stress-testing has shown that arrow presses are being registered and acted on even after the point at which the listener should be removed. Any thoughts on why this might be?

Thanks for reading.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda